package com.king.juc.syncmode;

import com.king.juc.terminationmode.TwoStageTerminationMode;
import lombok.extern.slf4j.Slf4j;

/**
 * 同步模式之Balking
 *
 * @author king
 * @date 2020/11/27 22:15
 */
@Slf4j(topic = "c.Balking")
public class Balking {
    private Thread monitor;
    /**
     * 标记停止
     */
    private volatile boolean stop;
    /**
     * 判断是否已启动监控
     */
    private volatile boolean starting = false;

    /**
     * 启动监控线程
     */
    public void start() {
        synchronized (this){
            if(starting){
                return;
            }
            starting = true;
        }
        monitor = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                if (stop) {
                    log.debug("后续收尾逻辑.....");
                    starting = false;
                    break;
                }

                try {
                    // 情况1
                    Thread.sleep(1000);
                    // 情况2
                    log.debug("执行监控记录.....");
                } catch (InterruptedException e) {
                    // sleep出现异常后, 会清除打断标记
                    // 设置打断标记
                    current.interrupt();
                }
            }
        });

        monitor.start();
    }

    /**
     * 停止监控线程
     */
    public void stop() {
        starting = !(stop = true);
        monitor.interrupt();
    }

    public static void main(String[] args) throws InterruptedException {
        Balking tpt = new Balking();
        tpt.start();

        Thread.sleep(3500);
        log.debug("停止监控......");
        tpt.stop();
    }
}
